// app.js
const kugou = require("./utils/kugouMusic");
const backgroundAudioManager = wx.getBackgroundAudioManager();
const theme = require("./utils/theme");
const { currentConfig, sharedConfig } = require("./utils/cloudConfig");

App({
  // 引入`towxml3.0`解析方法
  towxml: require("/towxml/index"),
  onLaunch() {
    const that = this;
    const {
      miniProgram: { envVersion },
    } = wx.getAccountInfoSync();
    switch (envVersion) {
      case "develop":
        this.globalData.hide = false;
        break;
      case "trial":
        this.globalData.hide = true;
        break;
      case "release":
        this.globalData.hide = false;
        break;
      default:
        this.globalData.hide = false;
        break;
    }

    // 初始化当前小程序的云开发环境
    wx.cloud.init({
      env: currentConfig.env, // 当前小程序环境 ID
      appid: currentConfig.appid, // 当前小程序 AppID
      traceUser: true, // 开启用户追踪（可选）
    });

    // 初始化共享云开发环境
    this.initSharedCloud();

    // wx.getSystemInfoAsync({
    //   success(res) {
    //     console.log(res.theme);
    //     that.globalData.globalTheme = res.theme
    //   }
    // })

    const themeType = wx.getStorageSync("themeType");
    if (themeType) {
      this.globalData.themeType = themeType;
    } else {
      this.globalData.themeType = "default";
    }

    this.overShare();
  },

  // 初始化共享云开发环境
  async initSharedCloud() {
    try {
      // 创建共享云开发实例
      const sharedCloud = new wx.cloud.Cloud({
        resourceAppid: sharedConfig.resourceAppid, // 资源方小程序 AppID
        resourceEnv: sharedConfig.resourceEnv, // 资源方环境 ID
      });

      // 初始化共享云开发环境
      await sharedCloud.init();

      // 将共享云开发实例保存到全局数据中
      this.globalData.sharedCloud = sharedCloud;
      this.globalData.sharedCloudReady = true; // 标记初始化完成

      console.log("共享云开发环境初始化成功");

      // 触发初始化完成事件
      this.triggerSharedCloudReady();
    } catch (error) {
      console.error("共享云开发环境初始化失败:", error);
      this.globalData.sharedCloudReady = false;
    }
  },

  // 触发共享云开发环境初始化完成事件
  triggerSharedCloudReady() {
    if (
      this.globalData.sharedCloudReadyCallbacks &&
      this.globalData.sharedCloudReadyCallbacks.length > 0
    ) {
      this.globalData.sharedCloudReadyCallbacks.forEach((callback) => {
        try {
          callback();
        } catch (error) {
          console.error("执行共享云开发环境就绪回调失败:", error);
        }
      });
      this.globalData.sharedCloudReadyCallbacks = [];
    }
  },

  // 等待共享云开发环境初始化完成
  waitForSharedCloudReady() {
    return new Promise((resolve, reject) => {
      if (this.globalData.sharedCloudReady) {
        resolve();
      } else {
        // 添加回调到队列
        if (!this.globalData.sharedCloudReadyCallbacks) {
          this.globalData.sharedCloudReadyCallbacks = [];
        }
        this.globalData.sharedCloudReadyCallbacks.push(resolve);

        // 设置超时
        setTimeout(() => {
          reject(new Error("共享云开发环境初始化超时"));
        }, 10000); // 10秒超时
      }
    });
  },

  // 全局分享
  overShare: function () {
    //间接实现全局设置分享内容
    wx.onAppRoute(function (res) {
      //获取加载的页面
      let pages = getCurrentPages(),
        //获取当前页面的对象
        view = pages[pages.length - 1],
        data;
      if (view) {
        data = view.data;
        if (!data.isOverShare) {
          data.isOverShare = true;

          //分享给好友
          view.onShareAppMessage = function () {
            return {
              title: "前端佬带你学前端",
              path: view.route, //分享页面地址
              imageUrl: "/static/img/logo.png",
            };
          };

          //分享朋友圈
          view.onShareTimeline = function () {
            return {
              title: "前端佬带你学前端",
              path: view.route, //分享页面地址
              imageUrl: "/static/img/logo.png",
              // 具体其他参数详见小程序开放平台
            };
          };
        }
      }
    });
  },
  handleMusic(_switch, callback) {
    const that = this;
    if (_switch) {
      backgroundAudioManager.pause();
      backgroundAudioManager.onPause(() => {
        that.globalData.isPlay = false;
        callback();
      });
    } else {
      backgroundAudioManager.play();
      backgroundAudioManager.onPlay(() => {
        that.globalData.isPlay = true;
        callback();
      });
    }
  },
  setMisic(current, callback, callback1, callback2) {
    const that = this;
    // let { myInterval } = that.data;
    // clearInterval(myInterval);
    backgroundAudioManager.startTime = 0;
    backgroundAudioManager.currentTime = 0;
    backgroundAudioManager.title = current.songName;
    backgroundAudioManager.src = current.url;
    backgroundAudioManager.singer = current.singerName;
    backgroundAudioManager.coverImgUrl = current.album_img;

    backgroundAudioManager.onPlay(() => {
      callback1();
    });
    backgroundAudioManager.onPause(() => {
      callback2();
    });
    backgroundAudioManager.onEnded(() => {
      callback();
    });
    backgroundAudioManager.onStop(() => {
      callback();
    });
    // this.playMusicError();

    // myInterval = setInterval(() => {
    //   //判断滑块是否在推动
    //   if (that.data.flag === false) {
    //     let a =
    //       dayjs(backgroundAudioManager.duration * 1000).format("mm:ss") ||
    //       "00:00"; //总时长 用dayjs对总时长进行处理
    //     let b = parseInt(backgroundAudioManager.duration); //滑块最大值
    //     let c =
    //       dayjs(backgroundAudioManager.currentTime * 1000).format("mm:ss") ||
    //       "00:00"; //当前时长
    //     let d = parseInt(backgroundAudioManager.currentTime); //滑块值
    //     // this.setData({
    //     //   totalTime: a, ///总时长 对数据进行处理后
    //     //   max: b, //滑块最大数
    //     //   currentTime: c,
    //     //   value: d,
    //     // });

    //     app.globalData.totalTime = a;
    //     app.globalData.max = b;
    //     app.globalData.currentTime = c;
    //     app.globalData.value = d;
    //     app.globalData.isPlay = true;

    //     // console.log("定时器", this.data.currentTime);
    //     backgroundAudioManager.onEnded(() => {
    //       clearInterval(myInterval);
    //       that.setData({ isPlay: false, currentHash: '' });
    //     });
    //   }
    // }, 1000);
    // that.setData({
    //   myInterval
    // })
  },
  globalData: {
    themeType: "default",
    globalTheme: "",
    theme: "",
    hide: true,
    db: null,
    sharedCloud: null,
    sharedCloudReady: false, // 共享云开发环境是否初始化完成
    sharedCloudReadyCallbacks: [], // 等待初始化的回调队列
    totalTime: "00:00",
    max: "",
    currentTime: "00:00",
    value: "",
    isPlay: false,
    currentHash: "",
    currentMusicList: [],
  },
});
